package com.myzombieapocalypse.projectz.domain.hibernate;

import org.springframework.dao.DataAccessException;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import java.io.Serializable;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

public abstract class AbstractHibernateDAO<T> extends HibernateDaoSupport implements Serializable{

     public T get(T t) {
         return (T) getHibernateTemplate().get(t.getClass(),this);
     }

    public void save(T t) {
         getHibernateTemplate().save(t);
    }

    public List<T> getAll() {
        List<T> tList = new ArrayList<T>();
        try {
            List list = getHibernateTemplate().loadAll(getGenericClass());
            for(Object o : list) {
                tList.add((T)o);
            }
        }catch (DataAccessException e) {
             tList = null;
        }
        return tList;
    }

    public Class getGenericClass() {
        Class result = null;
        Type type = this.getClass().getGenericSuperclass();

        if(type instanceof ParameterizedType){
        ParameterizedType pt = (ParameterizedType) type;
        Type[] fieldArgTypes = pt.getActualTypeArguments();
        result = (Class) fieldArgTypes[0];
        }

        return result;
    }

    public void saveAll(List<T> ts) {
        for (T t : ts) {
            save(t);
        }
    }
}
